package com.cooper.mediadb.download;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.os.Environment;
import android.util.Log;

import com.cooper.android.comm.FileUtils;
import com.cooper.mediadb.online.AnalyzeVideo;
import com.cooper.mediadb.online.MediaSource;
import com.cooper.mediadb.online.OnlineMedia;
import com.cooper.resource.download.DownloadResource;
import com.cooper.scraper.HttpDownload;

public class MovieDownResAdapter extends DownloadResource {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5397282644988058341L;

	public final static String DOWN_SAVE_DIR_NAME = ".cooper_soft/moviedb/downloading/movie";

	private OnlineMedia movie;

	private MediaSource source;

	private String format;

	public MovieDownResAdapter(OnlineMedia movie, MediaSource source, String format) {
		super();
		this.movie = movie;
		this.source = source;
		this.format = format;
	}

	public OnlineMedia getMovie() {
		return movie;
	}

	@Override
	public File getDownloadingSaveDir() {
		return new File(Environment.getExternalStorageDirectory().toString()
				+ "/" + DOWN_SAVE_DIR_NAME + "/"
				+ FileUtils.stringToFileName(movie.getTitle()));
	}

	@Override
	public String getDownloadTitle() {
	
		return movie.getTitle();
	}

	@Override
	public List<DownloadItem> analyzeDownloadItem(HttpDownload httpDownload)
			throws PrepareException {
		Log.d("MovieDownResAdapter","analyzeDownloadItem:" + source);
		AnalyzeVideo analyzeVideo = AnalyzeVideo.createAnalyzeVideo(
				httpDownload, source, format);
		List<DownloadItem> result = new ArrayList<DownloadItem>();
		
		int retry = 0;
		while (!Thread.currentThread().isInterrupted()
				&& retry <= httpDownload.getParams().getRetryCount()) {
			int i = 1;
			try {
				for (String s : analyzeVideo.analyzeVideo()) {
					result.add(new DownloadItem(String.valueOf(i++), s));
				}
				break;
			} catch (Exception e) {
				Log.e("MovieDownResAdapter", "analyze fail", e);
				result.clear();
				retry++;
			}
		}
		Log.d("MovieDownResAdapter","analyzeDownloadItem count:" + result.size());
		if (!Thread.currentThread().isInterrupted() && result.isEmpty()) {
			throw new PrepareException();
		} else
			return result;

	}

	@Override
	public String getThumbUrl() {
		return movie.getFanartUrl();
	}

	@Override
	public String getReferer() {
		return movie.getReferer();
	}

}
